package com.yj.forum.services.impl;

import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.dao.ArticleReplyMapper;
import com.yj.forum.exception.ApplicationException;
import com.yj.forum.model.ArticleReply;
import com.yj.forum.services.IArticleReplyService;
import com.yj.forum.services.IArticleService;
import com.yj.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    //注入dao
    @Resource
    ArticleReplyMapper articleReplyMapper;
    @Resource
    IArticleService articleService;
    /**
     * 新增回复
     * @param articleReply 回复信息
     */
    @Override
    public void create(ArticleReply articleReply) {
        //非空校验
        if(articleReply == null ||
                articleReply.getArticleId() == null
                || StringUtil.isEmpty(articleReply.getContent())
                || articleReply.getPostUserId() == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+" 回复内容不能为空或者该文章不存在 ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 填充默认数据
        articleReply.setState((byte) 0); // 状态
        articleReply.setDeleteState((byte) 0); // 是否状态
        articleReply.setLikeCount(0); // 点赞数量
        // 时间
        Date date = new Date();
        articleReply.setCreateTime(date); // 创建时间
        articleReply.setUpdateTime(date); // 更新时间
        // 写⼊回复数据
        int row = articleReplyMapper.insertSelective(articleReply);
        //校验
        if(row != 1) {
            log.info("新增帖⼦回复失败, userId = " + articleReply.getPostUserId() + ", articleId = " + articleReply.getArticleId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新帖子回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());

        log.info("新增帖⼦回复成功, userId = " + articleReply.getPostUserId() +
                ", articleId = " +  articleReply.getArticleId() + ", articleReplyId = " + articleReply.getId());
    }
    /**
     * 查询帖⼦对应的回复
     * @param articleId 帖⼦Id
     * @return "
     */
    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //非空校验
        if(articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+" 该文章不存在 articleId: "+articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        return articleReplies;
    }
}
